package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQuery;
import cn.wolfcode.service.IEmployeeService;
//import cn.wolfcode.utils.TokenManager;
import cn.wolfcode.utils.TokenManager;
import cn.wolfcode.vo.JsonResult;
import cn.wolfcode.vo.LoginInfo;
import cn.wolfcode.vo.Page;
import org.apache.ibatis.ognl.Token;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    private final IEmployeeService employeeService;

    public EmployeeController(IEmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @RequestMapping("/list")
    public JsonResult<Page<Employee>> query(EmployeeQuery qo) {
        //@RequestBody(required = false) 用get方法去掉它 用post方法使用他
        if (qo == null) {
            qo = new EmployeeQuery();
        }
        return JsonResult.success(employeeService.query(qo));
    }

    @RequestMapping("/getInfo")
    public JsonResult<LoginInfo> getInfo(@RequestHeader(value = TokenManager.TOKEN_NAME, required = false) String token) {
        // 从请求头中获取 token
       /* 方法1.
            1.参数写上HttpServletRequest req
            2.String token=req.getHeader("X-Token")*/

       //hasLength会有空格,hasText没有空格
        if (!StringUtils.hasText(token)) {
            return JsonResult.failed(400, "token 不能为空");
        }

        LoginInfo info = TokenManager.getInfo(token);
        return JsonResult.success(info);
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody//返回json要加这一句,如果整个类的方法 都返回Json 那么在类上面加
    public JsonResult<?> saveOrUpdate(@RequestBody Employee employee) {
        if (employee.getId() != null) {
            employeeService.updateById(employee);
        } else {
            employeeService.save(employee);
        }

        return JsonResult.success();
    }

    @RequestMapping("/delete")
    public JsonResult<?> delete(Long id) {
        if (id == null) {
            return JsonResult.failed("删除的 id 不能为空!");
        }

        employeeService.deleteById(id);
        return JsonResult.success();
    }
}
